﻿$(document).ready(function () {
    var nicesx = $("#boxscroll").niceScroll({ touchbehavior: false, cursorcolor: "#B0E2FF", cursoropacitymax: 0.9, cursorwidth: 7 });
});
var sVer = 0;
//$("input[id*='btnADDROW']").attr("disabled", true);
function btnSearch_Click(p_PageIndex) {
    var message = "";
    //檢核
    
    if ($("#MainContent_ddldept option:selected").val() == "" ) {
        message = "請選擇部門！\n";
    }
    if ($("#MainContent_txtCategory").val() == "") {
        message = message + "請輸入類別代號！\n";
    }
    if (message.length > 0) {
        alert(message);
        return false;
    }
    
    //將查詢條件記錄
    $("input[id*='hidddldept']").val($("#MainContent_ddldept option:selected").val()) ;
    $("input[id*='hidddlCategory']").val($("#MainContent_txtCategory").val());
    var sDEPT_ID = $("#MainContent_ddldept option:selected").val();
    var sCATEGORY_ID = $("#MainContent_txtCategory").val();
    //ddlCategory_reset(sDEPT_ID);
    
    var DetailTable = $("#MainContent_DetailTable")[0];
    var sType = '';
    
    var sFunction = '';
    var STATUS = "", DATA_SEQ = "", Document = "", Document_name = "";

    //清除Table
    var rowcut = DetailTable.rows.length;
    while (rowcut > 0) {
        DetailTable.deleteRow(0);
        rowcut = DetailTable.rows.length;
    }



    $('div.' + 'round').block({
        fadeIn: 700,
        fadeOut: 700,
        message: "<img src=\"" + g_BlockIMG + "\" /> ", css: {
            border: 'none',
            padding: '0px',
            opacity: .8
        },
        overlayCSS: { backgroundColor: g_BlockBG },
        onBlock: function () {
            $.ajax({
                type: "POST",
                url: "bas_category.aspx/CATEGORY",
                data: "{'DEPT_ID' : '" + sDEPT_ID + "','CATEGORY_ID' : '" + sCATEGORY_ID + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (xmlHttpRequest, error) {
                    var m_ErrMessage = xmlHttpRequest.responseText;

                    MsgBlock("round", m_ErrMessage, false);

                },
                success: function (data) {
                    if (data != null) {
                        $("input[id*='btnADDROW']").attr("disabled", false);
                        if (data.d.indexOf("error") >= 0) {
                            if (data.d.indexOf("error_no") < 0) {
                                alert(data.d.replace("error", ""));
                            }
                            else
                            {
                                
                                Add_Detail('A', "", "", "", "","0","Y");
                                AddDetailList_N(DetailTable, "", 15);//新增空白欄

                            }
                        }
                        else {
                            
                            $.each(data.d, function (RowCount, DataRow)
                            {
                                
                                Document = DataRow.DOCUMENT_NO;//表單代號
                                Document_name = DataRow.DOCUMENT_NAME;//表單名稱
                                DATA_SEQ = DataRow.DATA_SEQ;//類別代號
                                STATUS = DataRow.STATUS;//類別名稱
                                Add_Detail('U', Document, Document_name, sDEPT_ID,sCATEGORY_ID, DATA_SEQ, STATUS);
                                
                            });
                            Add_Detail('A', "", "", "", "", "0", "Y");
                            AddDetailList_N(DetailTable, "", 15);//新增空白欄
                        }
                    }
                    unblockUI("round");
                }

            });
        }
    });

    

}


function Add_Detail(stype, Document, Document_name,Dept_ID,Category, DATA_SEQ, STATUS) {
    //var tbody = document.getElementById(tblGV);
    var row;
    var rowcut;
    var cell;
    var sHTML
    var tbody = $("#MainContent_DetailTable")[0];
    
    var rowcount = tbody.rows.length;
    //row = tbody.insertRow();
    TR = document.createElement("TR");
    TR.id = "detlRow"
    for (var j = 0; j < 5; j++) {
        cell = document.createElement("TD");
        sHTML = "";
        switch (j) {
            case 0:
                cell.width = "5%";
                if (stype != "Q") {

                    //刪除Image
                    sHTML = "<input type='image' id='IMG_Del_" + sVer.toString() + '_' + rowcount + "'  name = 'IMG_Del_' src='../../Images/Delete.gif' onclick='DeleteRow(event,this.id);' />"
                    sHTML = sHTML + "<input type='hidden' name='hidDept_ID' id='hidDept_ID' value='" + Dept_ID + "' />";
                    sHTML = sHTML + "<input type='hidden' name='hidCategory' id='hidCategory' value='" + Category + "' />";
                }
                break;
            case 1:
                cell.width = "25%";
                if (stype == "Q") {
                    sHTML = " <span id='lblDocument' > " + Document + " </span>";
                }
                else {
                    sHTML = " <input type='text' id='txtDocument' maxlength='20' name = 'txtDocument' style='width:90%' value='" + Document + "'  /></td>";
                }
                break;
            case 2:
                cell.width = "40%";
                if (stype == "Q") {
                    sHTML = " <span id='lblDocument_name' > " + Document_name + " </span>";
                }
                else {
                    sHTML = " <input type='text' id='txtDocument_Name' maxlength='100' name = 'txtDocument_Name' style='width:90%' value='" + Document_name + "'  /></td>";
                }
                break;
            case 3:
                cell.width = "15%";
                if (stype == "Q") {
                    sHTML = " <span id='lblDATA_SEQ' > " + DATA_SEQ + " </span>";
                }
                else {
                    sHTML = " <input type='text' id='txtDATA_SEQ' maxlength='2' name = 'txtDATA_SEQ' style='width:90%' value='" + DATA_SEQ + "'  /></td>";
                }
                break;
            case 4:
                cell.width = "15%";
                if (stype == "Q") {
                    sHTML = " <span id='lblSTATUS' > " + STATUS + " </span>";
                }
                else {
                    sHTML = " <input type='text' id='txtSTATUS' maxlength='1' name = 'txtSTATUS' style='width:90%' value='" + STATUS + "'  /></td>";
                }
                break;
            
        }
        cell.innerHTML = sHTML;
        TR.appendChild(cell);
        
        
    }
    $("#MainContent_DetailTable").append(TR.outerHTML);
}

function Add_NEW_ROW() {
    //alert($("#MainContent_DetailTable")[0].rows.length);
    for (var j = 0; j < 20; j++) {
        Add_Detail('A', "", "", "", "", "", "0", "Y");

    }
}

function SEQ() {

    //檢核
    if ($("#MainContent_ddldept option:selected").val() == "" || $("#MainContent_txtCategory").val() == "") {
        alert("請選擇部門及輸入類別代號！")
        return false;
    }
    var DetailTable = $("#MainContent_DetailTable")[0];
    Add_Detail('A', "", "", "", "", "", "0", "Y");
    AddDetailList_N(DetailTable, "", 20);
    
}


function AddDetailList_N(DetailTable, seq, rows) {
    if (rows == "" || rows == undefined)
        //2005/4/20以便沒傳ROWS也可以增加空白欄位by samantha
    {
        rows = 10;
    }
    sVer = sVer + 1;
    var selectedIndex = $("#MainContent_DetailTable tr").length;
    var rowCount = $("#MainContent_DetailTable tr").length;
    for (i = 0; i < rows; i++) {
        var TR_Html = "";
        var row = selectedIndex - 1
        var Html = "",tr_HTML = "";
        var m_tr,m_td;
        m_tr = $("#MainContent_DetailTable tr:last td")
        $(m_tr).each(function (td_index) {
            m_td = $(this)[0]
            
            //if (td_index != seq)//seq不修改其idt
            //{
            $.each(m_td.children, function (index, m_ctrl) {
               m_ctrl.id = m_ctrl.name + sVer.toString() + '_' + (rowCount + i).toString();
                //Html = Html.replace(m_ctrl.id, m_ctrl.name + sVer.toString() + '_' + (rowCount + i).toString())
                switch (m_ctrl.type) {
                    case "checkbox":
                                    
                        break;
                    case "hidden":
                        m_ctrl.value = "";
                        break;
                    case "text":
                        if ((m_ctrl.name != "txtDATA_SEQ" && m_ctrl.name != "txtSTATUS") && m_ctrl.value != "") {
                            m_ctrl.value = "";
                            m_ctrl.defaultValue = "";
                            m_ctrl.disabled = false;
                            if (m_ctrl.style.background != "")
                                m_ctrl.style.background = "";

                        }
                                    
                        break;
                    case "select-one":
                                    
                        break;
                }
                   
                });
            //}
            Html += "<td>" + m_td.innerHTML + "</td>";
            if ($(this)[0].children.length == 0) {
                Html = ""
            }
        });
        TR_Html = "<tr> " + Html + "</tr>";
        $("#MainContent_DetailTable").append(TR_Html);
    }
}


function DeleteRow(e, p_ButtonID) {
    var obj = GetEvent(e)
    if ($("#" + obj.id).parent().length > 0) {
        var m_Tr = $("#" + obj.id).parent().parent()[0];
        var index = m_Tr.rowIndex;


        var tbody = $("#MainContent_DetailTable")[0];
        tbody.deleteRow(index);
    }
    
   
}

function Maintain_Save() {
    $("input[id*='txt']").each(function () {

        this.value = $.trim(this.value);

    });
    //檢核
    var message = "";
    if ($("#MainContent_ddldept option:selected").val() == "") {
        message = "請選擇部門！\n";
    }
    if ($("#MainContent_txtCategory").val() == "") {
        message = message + "請輸入類別代號！\n";
    }
    if ($("#MainContent_txtCategory_NAME").val() == "") {
        message = message + "請輸入類別名稱！\n";
    }

    var DetailTable = $("#MainContent_DetailTable")[0];
    if (DetailTable.rows.length == 0) {
        message = message + "請至少輸入一筆資料！\n"
    }
    

    var DetlRows
    var m_DetlCtrls = "";
    
    for (var j = 0; j < DetailTable.rows.length; j++) {
        if (DetailTable.rows[j].cells[1].children[0].value != "")
        {
            if(DetailTable.rows[j].cells[2].children[0].value == "")
            {
                message = message + "請輸入表單名稱\n";
                DetailTable.rows[j].cells[2].children[0].focus();
                
            }
            //排序欄位是否為數字
            if (DetailTable.rows[j].cells[3].children[0].value != "" && isNaN(DetailTable.rows[j].cells[3].children[0].value) ) {
                message = message + "排序請輸入數字型態\n";
                DetailTable.rows[j].cells[3].children[0].focus();
                
            }
        }
        if (DetailTable.rows[j].cells[2].children[0].value != "") {
            if (DetailTable.rows[j].cells[1].children[0].value == "") {
                message = message + "請輸入表單代號!\n";
                DetailTable.rows[j].cells[1].children[0].focus();
                
            }
            
        }

        if (message.length > 0) {
            alert(message);
            return false;
        }
        
        //if (DetailTable.rows[j].cells[1].children[0].value != "" && DetailTable.rows[j].cells[3].children[0].value != "") {
            m_DetlCtrls += "{";
            m_DetlCtrls += "'" + "Dept_ID" + "':'" + $("input[id*='hidddldept']").val() + "',";
            m_DetlCtrls += "'" + "Document" + "':'" + DetailTable.rows[j].cells[1].children[0].value + "',";
            m_DetlCtrls += "'" + "Document_NAME" + "':'" + DetailTable.rows[j].cells[2].children[0].value + "',";
            m_DetlCtrls += "'" + "DATA_SEQ" + "':'" + DetailTable.rows[j].cells[3].children[0].value + "',";
            m_DetlCtrls += "'" + "STATUS" + "':'" + DetailTable.rows[j].cells[4].children[0].value + "',";
            m_DetlCtrls += "'" + "USER" + "':'" + $("input[id*='hiUSER_ID']").val() + "'";
            //m_DetlCtrls += "'ACTION_TYPE':'" + "A" + "'";
            m_DetlCtrls += "},";
        //}
    }
    



    m_DetlCtrls = "[" + m_DetlCtrls;
    m_DetlCtrls = m_DetlCtrls.substr(0, m_DetlCtrls.lastIndexOf(",")) + "]";
   
    $.ajax({
        type: "POST",
        url: "bas_category.aspx/Maintain_Save",
        //data: "{ DetlCtrls : " + m_DetlCtrls + "}",
        data: "{ Dept_ID :'" + $("input[id*='hidddldept']").val() + "',Category : '" + $("input[id*='hidddlCategory']").val() + "',Category_NAME : '" + $("input[id*='txtCategory_NAME']").val() + "',DetlCtrls : " + m_DetlCtrls + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error) {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
            
        },
        success: function (data) {
            if (data != null) {
                if (data.d.indexOf("error") >= 0) {
                    if (data.d.indexOf("error_no") < 0) {
                        alert(data.d.replace("error", ""));
                    }
                }
                else {
                    btnSearch_Click()
                    alert(data.d);
                }
            }
            
        }
    });
    return false;
}

function Category_change(Dept_ID, CATEGORY_ID) {
    $("#MainContent_txtCategory_NAME").val("");
    $.ajax({
        type: "POST",
        url: "bas_category.aspx/getCATEGORY",
        data: "{'DEPT_ID' : '" + Dept_ID + "','CATEGORY_ID' : '" + CATEGORY_ID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xmlHttpRequest, error) {
            var m_ErrMessage = xmlHttpRequest.responseText;
            alert(m_ErrMessage);
        },
        success: function (data) {
            if (data != null) {
                if (data.d.indexOf("error") >= 0) {
                    if (data.d.indexOf("error_no") < 0) {
                        alert(data.d.replace("error", ""));
                    }

                }
                else {
                    $("#MainContent_txtCategory_NAME").val(data.d);
                }
            }

        }

    });
}

$(document).ready( function (){ 
    $("#MainContent_ddldept").change(function () { //事件發生

        //若Table中有從資料庫中撈出的資料，提醒使用者資料將重新載入
        var tbody = $("#MainContent_DetailTable")[0];
        for (var i = 0; i < tbody.rows.length - 1; i++) {
            if (tbody.rows[i].cells[0].children[1].value != "" && tbody.rows[i].cells[0].children[1].value != $(this).val()) {
                if (confirm(" 您已重新選擇部門代號,必需重新取得資料，確定資料要重新載入？ ") ) 
                {
                
                    btnSearch_Click();
                }　　　　　　
                else 　 
                {
                
                    $("#MainContent_ddldept").children().each(function () {
                        if ($(this).val() == tbody.rows[i].cells[0].children[1].value) {
                            //javascript給法
                            this.selected = true;
                        }
                    });
                }
                return false;
            }      
        }
        $("#MainContent_txtCategory").val("");
        $("#MainContent_txtCategory_NAME").val("");
    });

    $("#MainContent_txtCategory").change(function () { //事件發生
        var tbody = $("#MainContent_DetailTable")[0];
        for (var i = 0; i < tbody.rows.length - 1; i++) {
            if (tbody.rows[i].cells[0].children[2].value != "" && tbody.rows[i].cells[0].children[2].value != $(this).val()) {
                if (confirm(" 您已重新輸入類別代號,必需重新取得資料，確定資料要重新載入？ ")) {
                    btnSearch_Click();
                }
                else {
                    $(this).val(tbody.rows[i].cells[0].children[2].value);
                }
                
            }
        }
        //帶出類別中文
        Category_change($("#MainContent_ddldept").val(), $(this).val());
    });


});
function showModalPopupViaClient(ev) {
    var DEPT = "";
    DEPT = $("#MainContent_ddldept option:selected").val();
    
        var sORDER = '';
        sORDER = 'dept_id,category_id';
        //頁次
        //alert($("#MainContent_TabContainer2_TabPanel5_lblDetail_NO").html());
        //查詢條件 對應後端查詢條件
        var StrWhere = { DEPT_ID: DEPT };
        $("#mislandedPageControl").attr("GridWidth", "30%,35%,35%");
        $("#mislandedPageControl").attr("textalign", "C,C,C");
        $("#mislandedPageControl").attr("HideColumn", "");
        //組Grid 公用Function 後端網頁名稱, 查詢FUNCTION名稱, 頁次, 一頁筆數, 排序條件, 查詢條件, 目標 DIV
        gdb_DataBind("bas_category", "qtyCATEGORY", "1", "10", sORDER, StrWhere, "CATEGORY");

        
        var modalPopupBehavior = $("#ModalPopupExtender1");
        
    
}

function hideModalPopupViaClient(ev) {
    
}

function select(e, p_TargetDiv) {
    //擷取觸發控制項
    var obj = GetEvent(e);
    var sVALUE = "";
    switch (obj.tagName) {
        case "TD":
            if ($("#" + obj.id).parent().length > 0) {
                var m_TrId = $("#" + obj.id).parent()[0].id;
                SelectedRow(p_TargetDiv, m_TrId);
                sVALUE = $.trim($("#" + obj.id).parent()[0].cells[0].innerText).substring(0, 4);

                $("#MainContent_txtCategory").val($.trim($("#" + obj.id).parent()[0].cells[1].innerText));
                $("#MainContent_txtCategory_NAME").val($.trim($("#" + obj.id).parent()[0].cells[2].innerText));
                $('#MainContent_ddldept option[value=' + sVALUE + ']').attr('selected', true);
                $("#MainContent_txtCategory").change();
                $("#MainContent_btnClose")[0].click();
            }
            break;
    }
}